﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace IOP.Models.Data
{
    /// <summary>
    /// 可通知数据基类
    /// </summary>
    public class DataNotification : IDataNotification
    {
        /// <summary>
        /// 当属性发生变更后
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 当属性发生变更时
        /// </summary>
        public event PropertyChangingEventHandler PropertyChanging;
        /// <summary>
        /// 当属性发生变更后
        /// </summary>
        /// <param name="propertyName"></param>
        public virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        /// <summary>
        /// 当属性发生变更后
        /// </summary>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="expression"></param>
        public virtual void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> expression)
        {
            if (expression.Body is MemberExpression propertyNameExpresssion)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyNameExpresssion.Member.Name));
            }
        }
        /// <summary>
        /// 当属性发生变更时
        /// </summary>
        /// <param name="propertyName"></param>
        public virtual void OnPropertyChanging(string propertyName) => PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
        /// <summary>
        /// 当属性发生变更时
        /// </summary>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="expression"></param>
        public virtual void OnPropertyChanging<TProperty>(Expression<Func<TProperty>> expression)
        {
            if (expression.Body is MemberExpression propertyNameExpresssion)
            {
                PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyNameExpresssion.Member.Name));
            }
        }
    }
}
